using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Xna.Framework.Storage;
using System.Globalization;

namespace Fated.SaveEngine {
    public enum SaveFile { Character = 'c', Scenario = 's', Battle = 'b' }
    public static class SaveMngr {
        private static StorageContainer container;
        private static int defaultSaveIndex = 0;

        public static void initialize(StorageContainer c) {
            container = c;
        }
        public static void uninitialize() {
            if (container != null) {
                container.Dispose();
            }
        }
        public static void setSaveIndex(int idx) {
            defaultSaveIndex = idx;
        }

        public static void saveIJSONToFile(IJSON j, SaveFile s, int idx) {
            setSaveIndex(idx);
            saveDataToFile(j.ToJSON(), s);
        }
        public static void saveIJSONToFile(IJSON j, SaveFile s) {
            saveDataToFile(j.ToJSON(), s);
        }
        public static void saveDataToFile(Dictionary<string, object> j, SaveFile s){
            string filename = s + "." + defaultSaveIndex.ToString("D2");
            string toWrite = JSONSerializer.ToJSONString(j);

            if (container.FileExists(filename)) {
                container.DeleteFile(filename);
            }
            StreamWriter stream = new StreamWriter(container.CreateFile(filename));
            stream.Write(toWrite);

            stream.Flush();
            stream.Close();
        }

        public static string loadStringFromFile(SaveFile s, int idx) {
            defaultSaveIndex = idx;
            return loadStringFromFile(s);
        }
        public static string loadStringFromFile(SaveFile s) {
            string filename = s + "." + defaultSaveIndex.ToString("D2");

            StreamReader stream = new StreamReader(container.OpenFile(filename, FileMode.Open));
            string output = stream.ReadToEnd();

            stream.Close();

            return output;
        }
    }
}
